<script lang="ts" setup>
import { ref } from "vue"
import type { UploadUserFile } from "element-plus"
import { ElMessage, ElMessageBox } from "element-plus"
import * as XLSX from "xlsx"
import { getToken } from "@/utils/cache/cookies"

const { proxy } = getCurrentInstance()! as any
let dialogTableVisible = ref(false)
let dialogTableVisibleA = ref(false)
const DatasetName = ref({} as any)
const DatasetName1 = ref({} as any)
const rules = ref({} as any)
const wenjianjiay = ref({} as any)
const tableData = ref([] as any)
const tableData1 = ref([] as any)
const update = ref(true)
const update3 = ref({} as any)
const updataa = ref(false)
const zongshu = ref()
const maxParam = ref()
const maxOut = ref()
const maxOutArr = ref([])
const csize = ref()
const valueArr = ref([])
const options = ref([])
// const currentPage1 = ref(1)
const uploadHeader = {
  // "tenant-id": 1
  Authorization: "Bearer " + getToken()
}
const uploadData = ref({
  path: ""
})

let currentPage = ref(1)
let pageSize = ref(5)
let size = 'default'
let total = ref(0)
let tableRef1 = ref()
let description = ref("")
const matType = ref("")
const matThickness = ref("")
const ufName = ref("")
const queryParams = ref({
  dataName: '',
  dataThickness: '',
  newFileName: '',
  description: ''
})
let params = {
  dataName: '',
  dataThickness: '',
  newFileName: '',
  description: '',
  pageNo: currentPage.value,
  pageSize: pageSize.value,
  isAsc: false,
  orderBy: "createTime"
}
const rawCount = ref(0)
const filePath = ref("")
const gridData = ref([] as any)

const resetForm = () => {
  queryParams.value.dataName = ""
  queryParams.value.dataThickness = ""
  queryParams.value.newFileName = ""
  queryParams.value.description = ""
}

const onSubmit = (params?) => {
  params.dataName = queryParams.value.dataName
  params.dataThickness = queryParams.value.dataThickness
  params.newFileName = queryParams.value.newFileName
  params.description = queryParams.value.description
  const url = "/admin-api/wpes/dataSet/page"
  proxy.$http.get(url, {
    params
  }).then((v: any) => {
    if (v.data.code == 0) {
      gridData.value = v.data.data.list
      total.value = v.data.data.total
      if (checkedInput.value.length == 0) {
        v.data.data.list.forEach((value: any) => {
          checkedInput.value.push({ input: [], output: [] })
        })
      } else if (checkedInput.value.length < v.data.data.list.length) {
        /* 如果 新增数据集， 训练页面没刷新时，此时页面已渲染的数据集数目和实际数据库、接口的数目对不上，需要插入新增数据 */
        for (let j = 0; j < v.data.data.list.length - checkedInput.value.length; j++) {
          checkedInput.value.push({ input: [], output: [] })
        }
      }
    }
  })
}
const download = () => {
  dialogTableVisible.value = true
  // let a = document.createElement("a")
  // var event = new MouseEvent("click")
  // a.download = "template.xlsx" //这里除了是一个地址，还可以是一个Bolb对象 // url = URL.createObjectURL(url); // 创建blob地址 这里对于下载实现很重要！ 这个属性也决定了下载的文件名！！！
  // a.href = "/public/template/template.xlsx"
  // a.dispatchEvent(event) //触发a的点击事件！！！
}

const fileList = ref<UploadUserFile[]>([])
const beforeUpload = (f) => {
  if (f.name) {
    // uploadData.value.path = f.name;
  } else {
    ElMessage.error("网络错误，上传失败！！！")
  }
}
const uploadSuccess = (f: any) => {
  if (f.code === 0) {
    ElMessage.success("上传成功！")
    filePath.value = f.data
  }
}

const changeFile = (f: any) => {
  const fileReader = new FileReader()
  fileReader.readAsBinaryString(f.raw)
  // 这个readAsBinaryString一定要先提前执行，才可以出发fileReader.onload
  fileReader.onload = (ev) => {
    const workbook = XLSX.read(ev.target!.result, {
      type: "binary"
    })
    const wsname = workbook.SheetNames[0]
    const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])
    if (ws) {
      rawCount.value = ws.length
    }
  }
}
const clickSubmit = () => {
  if (matType.value == "" || matThickness.value == "" || ufName.value == "") {
    ElMessage.info("创建数据集需要填入上述信息！")
    return;
  } else if (!fileList.value[0]) {
    ElMessage.info("创建数据集需要上传excel数据文件！")
    return;
  }
  const data = {
    filePath: filePath.value,
    description: description.value,
    oldFileName: fileList.value[0].name,
    newFileName: ufName.value,
    dataName: matType.value,
    dataSize: rawCount.value,
    dataThickness: matThickness.value
  }
  const url = "/admin-api/wpes/dataSet/createDataSet"
  proxy.$http.post(url, data).then((v: any) => {
    if (v.data.code === 0) {
      ElMessage.success("创建数据集成功！")
      window.location.reload()
    }
  })
}
const createDatSet = () => {
  dialogTableVisibleA.value = true
}
const query = () => {
  onSubmit(params)
}
const throttle = () => { }
const checkedVal = ref(true)
const checkedInput = ref([] as any)
const tags = ref<Array<{ name: string; type: string }>>([])
const tags2 = ref<Array<{ name: string; type: string }>>([])
const tagInput = ref("")
const tagOutput = ref("")
const iAdd = () => {
  if (tagInput.value == '') {
    ElMessage.info('输入参数不能为空！')
    return
  }
  const bol = tags.value.some((t) => {
    return t.name == tagInput.value
  })
  if (!bol) {
    tags.value.push({ name: tagInput.value, type: "" })
    tagInput.value = ""
  } else {
    ElMessage.info('输入参数已存在！')
  }
}
const oAdd = () => {
  if (tagOutput.value == '') {
    ElMessage.info('输出参数不能为空！')
    return
  }
  const bol = tags2.value.some((t) => {
    return t.name == tagOutput.value
  })
  if (!bol) {
    tags2.value.push({ name: tagOutput.value, type: "" })
    tagOutput.value = ""
  } else {
    ElMessage.info('输出参数已存在！')
  }
}
const iReset = () => {
  tags.value = []
  tagInput.value = ""
}
const oReset = () => {
  tags2.value = []
  tagOutput.value = ""
}
const exportTemplate = () => {
  const len1 = tags.value.length
  const len2 = tags2.value.length
  const i = [] as any
  const o = [] as any
  tags.value.forEach((t) => {
    i.push(t.name)
  })
  tags2.value.forEach((t) => {
    o.push(t.name)
  })
  const params = {
    fileName: `template-i-${len1}-o-${len2}.xlsx`,
    inputParamNum: len1,
    outParamNum: len2,
    inputParamNames: i,
    outputParamNames: o
  }
  const url = "/admin-api/wpes/template/create"
  proxy.$http.post(url, params).then((v: any) => {
    if (v.data.code == 0) {
      const fileId = v.data.data
      const url = "/admin-api/wpes/template/getExcel"
      // 这里直接设置返回值responseType:'blob' ！！！ 而不是 { params: { id: fileId }, headers:{responseType:'blob'}}
      proxy.$http
        .get(url, { params: { id: fileId }, responseType: "blob", Authoriation: "Bearer " + getToken(), headers: {} })
        .then((v: any) => {
          // console.log(v)
          const dl = new Blob([v.data], { type: "application/vnd.ms-excel" })
          const url = URL.createObjectURL(dl)
          const a = document.createElement("a")
          const event = new MouseEvent("click")
          a.download = params.fileName // 创建blob地址,这个属性也决定了下载的文件名！！！
          a.href = url
          a.dispatchEvent(event) //触发a的点击事件！！！
          URL.revokeObjectURL(a.href)
        })
        .catch((e: any) => {
          console.log(e)
          ElMessage.error("下载出错了！请检查！")
        })
    }
  })
}
const resetAll = () => {
  tags.value = []
  tagInput.value = ""
  tags2.value = []
  tagOutput.value = ""
}
const handleCloseTag = (tag: any) => {
  tags.value.splice(tags.value.indexOf(tag.name), 1)
}
const handleCloseTag2 = (tag: any) => {
  tags2.value.splice(tags2.value.indexOf(tag.name), 1)
}
const flexColumnWidth = (str, arr1, flag = "max") => {
  // console.log(arr1)
  // str为该列的字段名(传字符串);tableData为该表格的数据源(传变量);
  // flag为可选值，可不传该参数,传参时可选'max'或'equal',默认为'max'
  // flag为'max'则设置列宽适配该列中最长的内容,flag为'equal'则设置列宽适配该列中第一行内容的长度。
  str = str + ""
  let columnContent = ""
  if (!arr1 || !arr1.length || arr1.length === 0 || arr1 === undefined) {
    return
  }
  if (!str || !str.length || str.length === 0 || str === undefined) {
    return
  }
  if (flag === "equal") {
    // 获取该列中第一个不为空的数据(内容)
    for (let i = 0; i < arr1.length; i++) {
      if (arr1[i][str].length > 0) {
        // console.log('该列数据[0]:', arr1[0][str])
        columnContent = arr1[i][str]
        break
      }
    }
  } else {
    // 获取该列中最长的数据(内容)
    let index = 0
    for (let i = 0; i < arr1.length; i++) {
      if (arr1[i][str] === null) {
        return
      }
      const now_temp = arr1[i][str] + ""
      const max_temp = arr1[index][str] + ""
      if (now_temp.length > max_temp.length) {
        index = i
      }
    }
    columnContent = arr1[index][str]
  }
  // console.log(columnContent)
  // console.log('该列数据[i]:', columnContent)
  // 以下分配的单位长度可根据实际需求进行调整
  let flexWidth = 0
  for (const char of columnContent + "") {
    if ((char >= "A" && char <= "Z") || (char >= "a" && char <= "z")) {
      // 如果是英文字符，为字符分配8个单位宽度
      flexWidth += 8
    } else if (char >= "\u4e00" && char <= "\u9fa5") {
      // 如果是中文字符，为字符分配15个单位宽度
      flexWidth += 15
    } else {
      // 其他种类字符，为字符分配8个单位宽度
      flexWidth += 9
    }
  }
  if (flexWidth < 80) {
    // 设置最小宽度
    flexWidth = 80
  }
  // if (flexWidth > 250) {
  //   // 设置最大宽度
  //   flexWidth = 250
  // }
  // console.log(flexWidth)
  return flexWidth + "px"
}
const deleteDataById = (rows: any) => {
  let url = '/admin-api/wpes/dataSet/deleteDataSet'
  let n = 0
  rows.forEach(r => {
    proxy.$http.post(url, {}, { params: { id: r.id } }).then(res => {
      if (res.data.code == 0) {
        n++
        if (n == rows.length) {
          ElMessage.success('删除成功')
          window.location.reload()
        }
      }
    })
  })

}
const deleteData = () => {
  let rows = tableRef1.value?.getSelectionRows()
  if (rows.length === 0) {
    ElMessage({
      message: "请选择要删除的数据",
      type: "error",
    })
    return
  }
  ElMessageBox.confirm("确定删除选中的数据集吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteDataById(rows)
    })
    .catch(() => { ElMessage.info('取消删除') })
}
const handleCurrentChange = (e) => {
  params.pageNo = e
  onSubmit(params)
}
onMounted(() => {
  onSubmit(params)
})
</script>

<template>
  <div class="dataManage-app" w-full h-full>
    <div class="css_cx" w-full h-full>
      <div class="css_cxc" w-full h-full>
        <div class="Updata my-5 mx-3">
          <el-button type="primary" @click="download">创建并下载模板</el-button>
          <el-button type="primary" @click="createDatSet">创建数据集<b class="text-red">*</b></el-button>
        </div>

        <el-form :inline="true" :model="DatasetName" :data="tableData" style="margin: 20px 10px"
          class="demo-form-inline" :rules="rules" ref="DatasetName">
          <el-form-item v-if="wenjianjiay" label="数据集名称：">
            <el-input style="width: 130px" v-model="queryParams.newFileName" :maxlength="15" placeholder="请输入数据集：" />
          </el-form-item>
          <el-form-item label="板材型号：" prop="dataName">
            <el-input style="width: 130px" :maxlength="15" v-model="queryParams.dataName" placeholder="请输入板材型号：" />
          </el-form-item>
          <el-form-item class="" label="板材厚度(mm)：" prop="dataThickness">
            <el-input type="number" style="width: 150px" v-model="queryParams.dataThickness" :maxlength="15"
              placeholder="请输入板材厚度：" />
          </el-form-item>

          <el-form-item v-if="wenjianjiay" label="描述：">
            <el-input style="width: 130px" v-model="queryParams.description" :maxlength="15" placeholder="请输入描述：" />
          </el-form-item>
          <!-- 选择文件输入框 -->

          <el-form-item>
            <el-button class="" type="primary" @click="query" v-if="update3">查询</el-button>
            <el-button class="" type="primary" @click="resetForm" v-if="update3">重置</el-button>
          </el-form-item>
        </el-form>

        <el-dialog class="overflow-hidden" @close="resetAll" v-model="dialogTableVisible" width="650" title="输入输出参数添加">
          <div class="inputDiv flex flex-row gap-6">
            <el-input style="width: 130px" :maxlength="15" v-model="tagInput" placeholder="请添加输入" />
            <el-button @click="iAdd">添加输入</el-button>
            <el-button @click="iReset">重置</el-button>
          </div>
          <div class="tags flex flex-col mt-3 items-center">
            <label class="mr-1 w-full" for="tags" v-if="tags.length > 0">当前有{{ tags.length }}输入参数</label>
            <div class="tagsWrap mt-2">
              <el-tag v-for="tag in tags" @close="handleCloseTag(tag)" :key="tag.name" class="mx-1" closable
                :type="tag.type as any">{{ tag.name }}
              </el-tag>
            </div>
          </div>
          <div class="outputDiv flex flex-row gap-6 mt-12">
            <el-input style="width: 130px" :maxlength="15" v-model="tagOutput" placeholder="请添加输出" />
            <el-button @click="oAdd">添加输出</el-button>
            <el-button @click="oReset">重置</el-button>
          </div>
          <div class="tags flex flex-col mt-3 items-center">
            <label for="tags" class="tagsWrap flex flex-row w-full" v-if="tags2.length > 0">当前有{{ tags2.length
              }}输出参数</label>
            <div class="tagsWrap mt-2">
              <el-tag v-for="tag in tags2" @close="handleCloseTag2(tag)" :key="tag.name" class="mx-1" closable
                :type="tag.type as any">{{ tag.name }}</el-tag>
            </div>
          </div>
          <div class="export text-right mt-15">
            <el-button type="info" @click="exportTemplate">输出模板</el-button>
          </div>
        </el-dialog>

        <el-dialog class="overflow-hidden" @close="resetAll" v-model="dialogTableVisibleA" width="1100" title="创建数据集">
          <div class="inputs">
            <el-form-item class="">
              <el-upload action="/admin-api/infra/file/upload" :data="uploadData" v-model:file-list="fileList"
                class="upload-demo" :headers="uploadHeader" :limit="3" :auto-upload="true" :on-change="changeFile"
                :before-upload="beforeUpload" :on-success="uploadSuccess">
                <el-button type="primary">上传数据<b class="text-red">*</b></el-button>
              </el-upload>
            </el-form-item>
            <el-form :inline="true" :model="DatasetName1" :data="tableData1" style="margin: 20px 0"
              class="demo-form-inline" :rules="rules" ref="DatasetName1">
              <el-form-item v-if="wenjianjiay" label="*数据集名称：">
                <el-input style="width: 130px" v-model="ufName" :maxlength="15" placeholder="请输入数据集：" />
              </el-form-item>
              <el-form-item label="*板材型号：" prop="dataName">
                <el-input style="width: 130px" :maxlength="15" v-model="matType" placeholder="请输入板材型号：" />
              </el-form-item>
              <el-form-item label="*板材厚度(mm)：" prop="dataThickness">
                <el-input type="number" style="width: 150px" v-model="matThickness" :maxlength="15"
                  placeholder="请输入板材厚度：" />
              </el-form-item>
              <el-form-item v-if="wenjianjiay" label="备注：">
                <el-input style="width: 130px" v-model="description" :maxlength="15" placeholder="请输入数据集：" />
              </el-form-item>


              <!-- 选择文件输入框 -->
            </el-form>
          </div>
          <div class="text-center">
            <el-button @click="clickSubmit">确认创建</el-button>
          </div>
        </el-dialog>
        <div class="deleteBtn p-5 -mt-6">
          <el-button type="default" @click="deleteData">删除数据集</el-button>
        </div>
        <el-table height="620" :data="gridData" class="!w-full" ref="tableRef1">
          <el-table-column type="selection" width="55" />
          <el-table-column align="center" property="id" label="数据集id" />
          <el-table-column :width="flexColumnWidth('newFileName', gridData)" align="center" property="newFileName"
            label="数据集名称">
            <template #default="column">
              <el-link :href="column.row.filePath" target="_blank">{{ column.row.newFileName }}</el-link>
            </template>
          </el-table-column>
          <el-table-column sortable :width="flexColumnWidth('createTime', gridData)" align="center"
            property="createTime" label="创建日期" />
          <el-table-column align="center" property="dataName" label="板材型号" />
          <el-table-column align="center" property="dataThickness" label="板材厚度" />
          <el-table-column width="205" align="center" property="dataSize" label="数据集数量" />
          <el-table-column align="center" property="inputParamNames" label="输入参数">
            <template #default="scope">
              <div class="">
                <el-checkbox-group
                  style="display: flex; flex-direction: column; align-items: center; justify-content: center"
                  v-model="checkedInput[scope.$index].input" @change="console.log(checkedInput, '/n', scope)">
                  <el-checkbox disabled class="w-full flex justify-center" :checked="checkedVal"
                    v-for="(i, index) in scope.row.inputParamNames" :key="index" :label="i">
                    {{ i }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" property="outParamNames" label="输出参数">
            <template #default="scope">
              <div class="">
                <el-checkbox-group style="display: flex; flex-direction: column; align-items: center"
                  v-model="checkedInput[scope.$index].output" @change="">
                  <el-checkbox disabled class="w-full flex justify-center" :checked="checkedVal"
                    v-for="(o, index) in scope.row.outParamNames" :key="index" :label="o">
                    {{ o }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" property="description" label="备注" />
        </el-table>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :size="size" :disabled="false"
          :background="true" layout="prev, pager, next, jumper" :total="total" @current-change="handleCurrentChange" />
        <div style="margin-left: 38px; margin: 37px">
          <div class="css_optiona"
            style="font-family: SourceHanSansCN-Medium; font-size: 18px; color: #333333; letter-spacing: 0"
            v-if="updataa">
            数据预处理
          </div>
          <div class="css_optiona"
            style="font-family: SourceHanSansCN-Normal; font-size: 16px; color: #999999; letter-spacing: 0"
            v-if="updataa">
            共{{ zongshu }}个参数，其中{{ maxParam }}个输入参数，{{ maxOut }}输出参数，共{{ csize }}条数据
          </div>
        </div>

        <div class="css_option" v-if="updataa">
          <div class="css_optiona">
            <p style="
                margin-left: 20px;
                font-family: SourceHanSansCN-Medium;
                font-size: 18px;
                color: #333333;
                letter-spacing: 0;
              ">
              输入参数
            </p>

            <div style="padding: 10px 10px" v-for="(key, index) in maxParam">
              <el-select label="选择文件：" v-model="valueArr[index]" placeholder="请选择">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>

            <el-button style="margin-left: 20px; margin-top: 30px" type="primary" v-if="updataa"
              @click="throttle('DatasetName')">保存</el-button>
          </div>

          <div class="css_optiona">
            <p style="
                margin-left: 20px;
                font-family: SourceHanSansCN-Medium;
                font-size: 18px;
                color: #333333;
                letter-spacing: 0;
              ">
              输出参数
            </p>
            <div style="padding: 10px 10px" v-for="(key, index) in maxOut">
              <el-select v-model="maxOutArr[index]" placeholder="请选择">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<style lang="scss" scoped>
@import "@/styles/dataManage.scss";

.el-checkbox:last-of-type {
  margin-right: 30px;
}
</style>
